#include <arduino.h>
#include <Wire.h>
#include "DHT.h"
#include "Adafruit_SGP30.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>


#define DHTPIN  2   
#define DHTTYPE DHT11

//用于存放温湿度；
float humidity;
float temperature;
float eTVOC;
float eCO2;
float light;
int counter = 0;
DHT dht(DHTPIN, DHTTYPE);  //温湿度在GPIO2;

//设定CO2传感器的温湿度；
uint32_t getAbsoluteHumidity(float temperature, float humidity) {
    const float absoluteHumidity = 216.7f * ((humidity / 100.0f) * 6.112f * exp((17.62f * temperature) / (243.12f + temperature)) / (273.15f + temperature));
    const uint32_t absoluteHumidityScaled = static_cast<uint32_t>(1000.0f * absoluteHumidity); 
    return absoluteHumidityScaled;
}
 

void setup() {
   Serial.begin(9600);
   dht.begin();
}

void loop() {
  humidity = dht.readHumidity();//读湿度
  temperature = dht.readTemperature();//读温度(摄氏度)
  
  Adafruit_SGP30 sgp;     //CO2的sda在GPIO4,scl在GPIO5;
  sgp.begin();
  if (! sgp.begin()){
    Serial.println("Sensor not found :(");
    while (1);
  }
  sgp.setHumidity(getAbsoluteHumidity(temperature, humidity));
  if (! sgp.IAQmeasure()) {
    Serial.println("Measurement failed");
    return;
  }
  eTVOC = sgp.TVOC;
  eCO2 = sgp.eCO2;
  counter++;
  if (counter == 30) {
    counter = 0;
    uint16_t TVOC_base, eCO2_base;
    if (! sgp.getIAQBaseline(&eCO2_base, &TVOC_base)) {
      Serial.println("Failed to get baseline readings");
      return;
    }
    sgp.setIAQBaseline(TVOC_base, eCO2_base);
  }

  
  Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
  tsl.begin();
  sensor_t sensor;
  tsl.getSensor(&sensor);
  delay(500);
  
  tsl.enableAutoRange(true);          
  tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); 
  
  sensors_event_t event;
  tsl.getEvent(&event);
  light = event.light;

   //串口输出传感器浓度；
  Serial.print("TVOC:"); 
  Serial.print(eTVOC); 
  Serial.println(" ppb");
  
  Serial.print("eCO2:"); 
  Serial.print(eCO2); 
  Serial.println(" ppm");
  
  Serial.print("湿度是：");
  Serial.print(humidity);
  Serial.println(" %RH");
  
  Serial.print("温度是：");
  Serial.print(temperature);
  Serial.println(" ℃");
  
  Serial.print("光强度：");
  Serial.print(light); 
  Serial.println(" lux");
  Serial.println("\n\n\n");
  delay(500);
  
  
}
